package com.gitee.elf.module.kether

import com.gitee.elf.core.entity.MetadataContainer.Companion.safeData
import taboolib.library.kether.ParsedAction
import taboolib.module.kether.*
import java.util.concurrent.CompletableFuture

class ActionMeta {

    class MetaSet(val id: String, val value: ParsedAction<*>) : ScriptAction<Void>() {

        override fun run(frame: ScriptFrame): CompletableFuture<Void> {
            return frame.newFrame(value).run<Any>().thenAccept {
                frame.getEntityMetadataContainer()[id] = it.safeData()
            }
        }

    }

    companion object {

        @KetherParser(["meta"], namespace = NAMESPACE)
        fun parser() = scriptParser {
            val id = it.nextToken()
            try {
                it.mark()
                it.expects("to")
                MetaSet(id, it.nextParsedAction())
            } catch (_: Exception) {
                actionNow {
                    if (id == "*" || id == "all") {
                        getEntityMetadataContainer().map()
                    } else {
                        getEntityMetadataContainer().get(id)?.bind?.getValue()
                    }
                }
            }
        }

    }

}